#pragma once
#include <iostream>
#include <string>
#include <memory>
#include <unistd.h>
#include "Socket.hpp"
#include "Log.hpp"
#include "Epoller.hpp"

using namespace NetWorkModule;
using namespace EpollerModule;

const static int gbacklog = 32;

// for debug
string EventToString(uint32_t events)
{
    string info;
    if (events & EPOLLIN)
        info += "EPOLLIN ";
    if (events & EPOLLOUT)
        info += "EPOLLOUT ";
    if (events & EPOLLET)
        info += "EPOLLET ";
    return info;
}

class EpollServer
{
    static const int maxevents = 64;

public:
    EpollServer(int port)
        : _port(port),
          _listensock(new TcpSocket()),
          _epoller(new Epoller()),
          _isrunning(false)
    {
    }
    ~EpollServer()
    {
    }

    bool InitServer()
    {
        // 1.创建listensock
        _listensock->BuildListenSocketMethod(_port, gbacklog);
        lg.LogMessage(Info, "init socket success, listensock is %d\n", _listensock->GetSockFd());
        // 2. 创建epoll模型
        _epoller->InitEpoller();
        lg.LogMessage(Info, "init epoller success\n");
        // 3.将listensock添加到epoll中
        _epoller->AddEvent(_listensock->GetSockFd(), EPOLLIN);
        return true;
    }

    bool Accepter(string *peerip, uint16_t *peerport)
    {
        // 监听事件就绪了
        int sockfd = _listensock->AcceptConnection(peerip, peerport);
        if (sockfd < 0)
        {
            lg.LogMessage(Warning, "accept error\n");
            return false;
        }
        // 获取连接成功
        _epoller->AddEvent(sockfd, EPOLLIN);
        return true;
    }
    int Recver(int sockfd, string *out)
    {
        char buffer[1024];
        int n = ::recv(sockfd, buffer, sizeof(buffer), 0);
        if (n > 0)
        {
            buffer[n] = 0;
            *out = buffer;
        }
        return n;
    }

    void HandlerEvent(int n)
    {
        lg.LogMessage(Debug, "%d 个 events 已经就绪了\n", n);
        for (int i = 0; i < n; i++)
        {
            lg.LogMessage(Debug, "ready fd: %d, Event is: %s\n",
                          _revs[i].data.fd, EventToString(_revs[i].events).c_str());
            int sockfd = _revs[i].data.fd;
            uint32_t events = _revs[i].events;
            if (events & EPOLLIN)
            {
                // 读事件分两种 1. listensock 2. normal sockfd
                if (sockfd == _listensock->GetSockFd())
                {
                    string clientip;
                    uint16_t clientport;
                    if (!Accepter(&clientip, &clientport))
                        continue;
                    lg.LogMessage(Info, "accept client success, client[%s:%d]\n",
                                  clientip.c_str(), clientport);
                }
                else
                {
                    string message;
                    int n = Recver(sockfd, &message); // 读取
                    if (n > 0)
                    {
                        cout << "client# " << message << endl;
                        message.resize(message.size()-strlen("\r\n"));
                        // 直接写
                        string echo_message = "echo message: " + message + "\r\n";
                        send(sockfd, echo_message.c_str(), echo_message.size(), 0);
                    }

                    else
                    {
                        if (n == 0)
                        {
                            lg.LogMessage(Info, "client %d close\n", sockfd);
                        }
                        else
                        {
                            lg.LogMessage(Info, "recv %d error\n", sockfd);
                        }
                        _epoller->DelEvent(sockfd); // 把事件的关心也要去掉，这个fd必须是合法的
                        close(sockfd);              // 先移除再关闭
                    }
                }
            }
        }
    }
    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            _epoller->DebugFdList();
            int timeout = -1; // 阻塞，方便测试
            int n = _epoller->Wait(_revs, maxevents, timeout);
            switch (n)
            {
            case 0:
                lg.LogMessage(Debug, "timeout...\n");
                break;
            case -1:
                lg.LogMessage(Error, "epoll wait failed!\n");
                break;
            default:
                // 事件就绪
                lg.LogMessage(Info, "event happend... \n");
                HandlerEvent(n);
                break;
            }
        }
        _isrunning = false;
    }

private:
    std::unique_ptr<Socket> _listensock;
    std::unique_ptr<Epoller> _epoller;
    uint16_t _port;
    bool _isrunning;
    struct epoll_event _revs[maxevents];
};
